#include "gateway/beast_http/response_adapter.hpp"

using namespace cpp_backend::framework;
namespace http = boost::beast::http;

namespace gateway::beast_http {

http::response<http::string_body> ResponseAdapter::ToBeast(const Response& resp) {
    http::response<http::string_body> res;
    res.version(11);
    res.result(static_cast<unsigned>(resp.GetHttpStatus()));
    res.set(http::field::content_type, "application/json");
    for (const auto& kv : resp.GetHeaders()) {
        res.set(kv.first, kv.second);
    }
    // body: 优先 data(JSON)，否则 raw body
    if (!resp.GetData().is_null()) {
        res.body() = resp.ToString();
    } else if (!resp.GetRawBody().empty()) {
        const auto& raw = resp.GetRawBody();
        res.body().assign(reinterpret_cast<const char*>(raw.data()), raw.size());
    } else {
        res.body() = resp.ToString(); // 至少返回code/message
    }
    res.prepare_payload();
    return res;
}

} // namespace gateway::beast_http

